<template>
  <div :class="['engineer-list', 'common-list-container__v2', {'engineer-over': !isEngineerList}, {'engineer-pad': isEngineerList}]">
    <div class="engineer-list-main pad-t-16">
      <!--搜索Start-->
      <div :class="['engineer-list-main-search', 'flex', {'main-btn': isEngineerList}]" ref="tableHeaderContainer">
        <div class="engineer-list-main-search-btn flex-x" v-if="!isEngineerList">
          <!--独立端显示新建工程师，钉钉端显示添加工程师，独立端的（添加工程师改名叫做恢复账号）在下面-->
          <el-button
            v-if="tenantType === 1"
            type="primary"
            @click="gotoUrl( 'PageServiceEngineerCreate')">{{$t('common.base.createEngineer')}}</el-button>
          <el-button
            v-else
            type="primary"
            @click="addEngineer">{{$t('common.base.addEngineer')}}</el-button>
          <el-button
            v-if="mapPeopleEnable"
            type="plain-third"
            @click="gotoMap">{{$t('common.base.engineerMap')}}</el-button>
        </div>
        <div class="flex-x">
          <div v-if="tenantType === 1&&!isEngineerList" class="mar-r-16 cur-point color-primary" @click="addEngineer">
            <span class="iconfont icon-huifu"></span>
            <span>{{$t('serviceProvider.recoverEngAccount')}}</span>
          </div>
          <el-input
              class="search-input mar-r-8"
              v-model="deptKeyword"
              :placeholder="$t('common.placeholder.inputEngineerNameOrPhone')"
              v-trim:blur
              @keyup.enter.native="searchList">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
          <el-dropdown>
            <div class="cur-point mar-r-8">
              <span>{{$t('common.base.moreOperator')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
            <el-dropdown-menu slot="dropdown" class="el-dropdown-provider">
              <el-dropdown-item >
                <div @click="openDialog('importEngineer')" v-if="tenantType == 1 && btnsPermission['providerEngineerImport']"> {{$t('common.base.import')}}</div>
              </el-dropdown-item>
              <el-dropdown-item >
                <div @click="openDialog('updateEngineerList')"  v-if="btnsPermission['edit']">{{$t('common.base.batchUpdate')}}</div>
              </el-dropdown-item>
              <el-dropdown-item >
                <div @click="exportProcider(false)" v-if="btnsPermission['providerEngineerExport']">{{$t('common.base.export')}}</div>
              </el-dropdown-item>
              <el-dropdown-item >
                <div @click="exportProcider(true)" v-if="btnsPermission['providerEngineerExport']">{{$t('common.base.exportAll')}}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <span class="el-dropdown cur-point mar-l-8" @click="handleSelectColumn">
          {{$t('common.base.choiceCol')}}
          <i class="iconfont icon-fdn-select"></i>
          </span>
        </div>
      </div>
      <!--搜索End-->

      <!--表格Start-->
      <div class="mar-t-16">
        <el-table
            v-table-style
            ref="tableRef"
            v-loading="listLoading"
            header-row-class-name="common-list-table-header__v2"
            :data="dataList"
            border
            class="bbx-normal-list-box"
            :height="tableContainerHeight"
            @select="handleSelection"
            @select-all="handleSelection"
        >
          <template slot="empty">
            <BaseListForNoData
                v-show="!listLoading"
                :notice-msg="$t('common.base.tip.noData')"
            ></BaseListForNoData>
          </template>
          <el-table-column
              type="selection"
              width="48"
              align="center"
              class-name="select-column"
          ></el-table-column>
          <template v-for="(column, index) in columns">
            <el-table-column
                v-if="column && column.show"
                show-overflow-tooltip
                :key="`${column.fieldName}_${index}`"
                :label="column.displayName"
                :min-width="column.minWidth"
                :prop="column.fieldName"
                :width="column.width"
                :resizable="true"
                :fixed="column.fixLeft || false"
            >
              <template slot-scope="scope">
                <!--工程师名称-->
                <template v-if="column.fieldName === 'name'">
                  <div
                    v-if="scope.row.name"
                    class="engineer-info-name c-primary cur-point"
                    @click="gotoUrl(
                      'PageServiceEngineerDetail',
                      scope.row.loginUserId ,
                      `id=${scope.row.loginUserId}&tenantProviderId=${scope.row.provider.tenantProviderId}`)">
                    {{ scope.row.name }}<div v-if="scope.row.isMain" class="engineer-main-people">{{$t('common.base.principal')}}</div>
                  </div>
                </template>
                <!--所属服务商-->
                <template v-else-if="column.fieldName === 'provider'">
                  <div v-if="scope.row.provider">{{ scope.row.provider.name }}</div>
                </template>
                <!--授权工单类型&授权产品类型-->
                <template v-else-if="column.fieldName === 'authorizeTask' || column.fieldName === 'authorizeProduct'">
                  {{ getAuthorize(scope.row[column.fieldName])}}
                </template>
                <!--授权区域-->
                <template v-else-if="column.fieldName === 'authorizeAddress'">
                  {{ getAreas(scope.row[column.fieldName])}}
                </template>
                <!--授权有效期-->
                <template v-else-if="column.fieldName === 'validTime'">
                  <div v-if="scope.row[column.fieldName]">{{ scope.row[column.fieldName].validTime | fmt_date }} {{$t('common.base.to')}} {{ scope.row[column.fieldName].inalidTime | fmt_date }}</div>
                </template>
                <!--上岗日期-->
                <template v-else-if="column.fieldName === 'engineerDate'">
                  <div>{{ scope.row[column.fieldName] | fmt_date }}</div>
                </template>
                <!--角色名称-->
                <template v-else-if="column.fieldName === 'role'">
                  <div v-if="scope.row[column.fieldName]"> {{ scope.row[column.fieldName].name }}</div>
                </template>
                <!--状态-->
                <template v-else-if="column.fieldName === 'status'">
                  <div>{{ getStatus(scope.row.status) }}</div>
                </template>
                <!-- 创建时间&更新时间-->
                <template v-else-if="column.fieldName === 'createTime' || column.fieldName === 'updateTime'">
                  {{ scope.row[column.fieldName] | fmt_datetime }}
                </template>
                <!-- 创建人&更新人 -->
                <template v-else-if="column.fieldName === 'createUser' || column.fieldName === 'updateUser'">
                  <div v-if="scope.row[column.fieldName]">{{ scope.row[column.fieldName].displayName || '' }}</div>
                </template>
                <!--联系地址-->
                <template v-else-if="column.fieldName === 'engineerAddress'">
                  {{ getAddress(scope.row[column.fieldName])}}
                </template>
                <!--地址-->
                <template v-else-if="column.fieldName === 'address'">
                  {{ getAddress(scope.row[column.fieldName])}}
                </template>
                <template v-else-if="column.fieldName === 'qualificationNames'">
                  {{ scope.row.qualificationNames && scope.row.qualificationNames.join('，')}}
                </template>
                <!-- 富文本 -->
                <template v-else-if="column.formType === 'richtext'">
                  <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
                    <span v-if="scope.row.formVOList && scope.row.formVOList[column.field]">{{$t('common.base.view')}}</span>
                  </div>
                </template>
                <template v-else-if="column.fieldName === 'loginStatus'">
                  <div class="flex-x table-blacklist">
                    <div :class="[findThisStatusClass(scope.row)]">{{ findThisStatusDes(scope.row) }}</div>
                    <div v-if="findThisStatusShowNote(scope.row)" class="flex-x mar-l-8 cur-point color-primary" @click="noteItem('service', scope.row)"><i class="iconfont icon-tongzhiweixuanzhong font-12-i mar-r-5"></i>{{ $t('common.base.remind') }}</div>
                  </div>
                </template>
                <template v-else>
                  {{
                    $formatFormField(column, scope.row, 'formVOList')
                  }}
                </template>
              </template>
            </el-table-column>
          </template>
          <el-table-column :label="$t('common.base.operation')" width="150px" fixed="right">
            <template slot-scope="scope">
              <div
                  v-if="btnsPermission['edit']"
                  @click="gotoUrl(
							   'PageServiceEngineerEdit',
								        scope.row.loginUserId,
								`id=${scope.row.loginUserId}&tenantProviderId=${scope.row.provider.tenantProviderId}`)">
                <span class="c-primary cur-point mar-r-12">{{$t('common.base.edit')}}</span>
              </div>
              <div v-if="btnsPermission['stop']"  @click="stopEngineer(scope.row)">
                <span class="c-primary cur-point mar-r-12">{{ scope.row.accountStatus === 1 ? $t('common.base.deactivate') : $t('common.base.enable')}}</span>
              </div>
              <div>
                <!--钉钉端不显示删除，重置密码按钮-->
                <template v-if="tenantType !== 1">
                  <span v-if="btnsPermission['delete']" class="c-primary cur-point mar-r-12" @click="logoutEngineer(scope.row)">{{$t('common.base.logout')}}</span>
                </template>
                <el-popover
                  v-else-if="btnsPermission['reset'] || btnsPermission['delete']"
                  popper-class="more-tip"
                  placement="left"
                  width="120"
                  trigger="hover"
                >
                  <div>
                    <div v-if="btnsPermission['reset']" class="engineer-more" @click="resetPassward(scope.row)">{{$t('common.base.resetPwd')}}</div>
                    <div v-if="btnsPermission['delete']" class="engineer-more" @click="deleteEngineer(scope.row)">{{$t('common.base.delete')}}</div>
                    <div v-if="btnsPermission['delete']" class="engineer-more" @click="logoutEngineer(scope.row)">{{$t('common.base.logout')}}</div>
                  </div>
                  <template slot="reference">
                    <span class="c-primary cur-point">{{$t('common.base.more')}}</span>
                  </template>
                </el-popover>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 Start -->
        <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer">
          <div class="list-info">
            <i18n path="common.base.table.totalCount">
              <span place="count" class="level-padding">{{ page.total }}</span>
            </i18n>
            <template v-if="multipleSelection && multipleSelection.length>0">
              <i18n path="common.base.table.selectedNth">
                <span place="count" class="color-primary pad-l-5 pad-r-5">{{ multipleSelection.length }}</span>
              </i18n>
              <span class="color-primary cur-point" @click="toggleClearSelection">{{$t('common.base.clear')}}</span>
            </template>
          </div>
          <el-pagination
              background
              @current-change="handlePageJump"
              @size-change="handleSizeChange"
              :page-sizes="defaultTableData.defaultPageSizes"
              :page-size="page.pageSize"
              :current-page="page.pageNum"
              layout="prev, pager, next, sizes, jumper"
              :total="page.total"
          >
          </el-pagination>
        </div>
        <!-- 分页 End -->
      </div>
      <!--表格End-->

      <!-- 选择列Start -->
      <biz-select-column ref="advanced" mode="provider" @save="saveColumnStatus" />
      <!-- 选择列End-->

      <!--设置主派单员-->
      <main-dispatcher ref="mainDisRef" @refresh="resetSearch"></main-dispatcher>
      <!--重置密码-->
      <reset-password ref="resetPasRef"></reset-password>
      <!--添加工程师-->
      <add-user ref="addUserRef" @refresh="resetSearch(true)"></add-user>
    </div>
    <!-- start 导入 -->
    <base-import :title="$t('common.base.importEngineer')" ref="importModal" :action="providerBaseImportFile" :uploadParamObject="uploadParamObject" >
      <div slot="tip">
        <div class="base-import-warn">
          <i18n path="common.base.importModal.downloadTemplateTip">
            <a :href="`${providerBaseImportTemplate}?type=2`" place="link">{{$t('common.base.importModal.importTemplate')}}</a>
          </i18n>
        </div>
      </div>
    </base-import>
    <!-- end 导入 -->

    <!-- start 批量更新 -->
    <biz-batch-update
      ref="batchUpdateDialog"
      :selected-ids="selectedIds"
      :total-items="page.total"
      :upload-param-object="uploadParamObject"
      :batch-update-template="batchUpdateUrlTemplate"
      :uploadParamObject="uploadParamObject"
      :isPostBatch="true"
      :title="$t('component.bizBatchUpdate.engineerTitle')"
      :moduleTitle="$t('common.base.engineer')"
      :action="providerOrEngineerUpdateBatch"
      @success="search"
    ></biz-batch-update>
    <!-- end 批量更新 -->

    <base-export
      ref="exportPanel"
      :columns="exportColumns"
      :build-params="buildExportParams"
      :validate="checkExportCount"
      :storage-key="exportStorageKey"
      method="post"
      :action="providerListExport"/>

    <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
  </div>
</template>

<script>
import { getRootWindowInitData } from '@src/util/window'
import { storageGet, storageSet } from "@src/util/storage";
import Page from '@model/Page';
import { TABLE_HEIGHT_MIN } from '@src/model/const/Number';
import _ from "lodash";
import { defaultTableData } from '@src/util/table'

//api
import {
  getServiceEngineerInit,
  getEngineerPageList,
  openEngineer,
  unbindUser,
  deleteEngineer,
  checkByReportKey
} from '@src/api/serviceProviderApi';

//component
import MainDispatcher from "../component/MainDispatcher";
import ResetPassword from "../component/ResetPassword";
import AddUser from "../component/AddUser";
import { openAccurateTab } from "@src/util/platform";
import { PageRoutesTypeEnum } from "@model/enum/PageRoutesEnum";
/* util */
import { formatDate, useFormTimezone } from 'pub-bbx-utils'
import { safeNewDate } from '@src/util/time';
/* export & import */
import { providerListExport } from '@src/api/Export';
import { providerBaseImportFile, providerBaseImportTemplate, batchUpdateUrlTemplate, providerOrEngineerUpdateBatch } from '@src/api/Import';
/* enum */
import StorageKeyEnum from '@model/enum/StorageKeyEnum'

const ENGINEER_LIST_KEY = 'engineer_list';
const ENGINEER_PAGE_SIZE_KEY = 'engineer_page_size';
import { formatAddress } from 'pub-bbx-utils';
import { t } from '@src/locales'

import { useStateNoteUserSendMessage } from '@src/modules/dept/mock.ts'

const { findThisStatus, findThisStatusDes, findThisStatusClass, findThisStatusShowNote, noteItem, haveUserNote } = useStateNoteUserSendMessage()
export default {
  name: "EngineerList",
  props: {
    shareData: {
      type: Object,
      default: () => ({
        status: '1',
        hideTopTip: false,
      })
    },
  },
  components: {
    MainDispatcher,
    ResetPassword,
    AddUser
  },
  computed: {
    // 是否是服务商
    isProviderUser() {
      return getRootWindowInitData().isProviderUser || false
    },

    // 0：钉钉端，1：自建，2：企微端
    tenantType() {
      return getRootWindowInitData().tenantType;
    },

    // 是否选中服务商显示工程师列表
    isEngineerList() {
     return !!this.shareData?.tenantProviderId
    },
    /* 已选择 id列表 */
    selectedIds() {
      return this.multipleSelection.map(item => item.loginUserId) || [];
    },
    exportColumns() {
      const needFilterForm = ['attachment','separator','info', 'autograph', 'imageDisplay'];
      this.columns.filter(item=> !needFilterForm.includes(item.formType) && item.fieldName !== 'qualificationNames')
      .map(v => {
        v.field = v.fieldName;
        v.label = v.displayName;
        v.export = true;
      });
      return this.columns;
    }
  },
  data() {
    return {
      exportStorageKey: StorageKeyEnum.EngineerListExport,
      providerOrEngineerUpdateBatch,
      batchUpdateUrlTemplate,
      providerListExport,
      providerBaseImportTemplate,
      providerBaseImportFile,
      defaultTableData,
      btnsPermission: [], // 按钮权限
      columns: [],
      deptKeyword: '',
      dataList: [], // 列表的数据
      listLoading: false,
      tableContainerHeight: `${TABLE_HEIGHT_MIN}px`, // 表格默认最小440px
      page: new Page(), // page 对象
      multipleSelection: [], // 勾选的数量,
      mapPeopleEnable: false, // 人员地图按钮是否显示
      uploadParamObject: {
        type: 2
      },
      haveUserNote,
    }
  },
  async mounted() {
    try {
      // 获取缓存的pagesize
      const localStorageData = await this.getLocalStorageData();
      this.page.pageSize = localStorageData[ENGINEER_PAGE_SIZE_KEY] || 10;
      // 获取人员地图权限
      this.checkByReportKey();
      // 获取表头
      await this.getInitInfo();
      // 获取表格数据
      this.search();

      let that_ = this;
      // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
      window.addEventListener('message', (event)=> {
        const {action} = event.data;
        if (action === 'shb.frame.activatedPage'){
          that_.$nextTick(()=> {
            that_.knowTableContainerHeight();
          })
        }
      });
      
      // 监听窗口变化
      window.addEventListener('resize', (event) => {
        this.debounceKnowTableContainerHeight()
      })
      
      this.$nextTick(()=> {
        this.knowTableContainerHeight()
        window.onresize = _.debounce(()=>{
          that_.knowTableContainerHeight()
        }, 500)
      })
    } catch (e) {
      console.error(e)
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.debounceKnowTableContainerHeight)
  },
  methods: {

    findThisStatus, 
    findThisStatusDes, 
    findThisStatusClass,
    findThisStatusShowNote,
    noteItem,
    /** 打开富文本弹窗 */
    openRichtextVisible(row, column) {
      const richtextId = row?.formVOList?.[column.fieldName] || ''
      this.$refs?.baseViewRichTextRef?.openDialog(richtextId)
    },
    /** 导出服务商 */
    exportProcider(exportAll) {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}${t('common.base.serviceProvider')}.xlsx`;
      if (!exportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert(t('common.base.tip.exportNoChoice'));
        ids = this.selectedIds;
      }
      this.$refs.exportPanel.open(ids, fileName);
    },
    /**打开导出弹窗 */
    openDialog(type) {
      if(type == 'importEngineer') {
        this.$refs.importModal.open();
      }else{
        this.$refs.batchUpdateDialog.openBatchUpdateCustomerDialog();
      }
    },
    /** 检测导出条数 */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.page.totalElements > max
        ? this.$t('common.base.tip.exportLimit', { max })
        : null;
    },
    /** 构建导出参数*/
    buildExportParams(checkedArr, ids) {
      let exportAll = !ids || !ids.length;

      return {
        searchModel: JSON.stringify({ ...this.buildSearchParams() }),
        exportTotal: exportAll ? this.page.total : ids.length,
        checked: checkedArr.join(','),
        idList: exportAll ? [] : ids,
        ...this.uploadParamObject
      };
    },
     async checkByReportKey() {
      try {
        let res = await checkByReportKey({reportKey: 'PERMAP'});
        if(res?.success) {
          this.mapPeopleEnable = res?.data || false;
        }
      } catch (e) {
        console.error(e)
      }
     },
    // 获取表头数据
    async getInitInfo() {
      try {
        let isProviderUser = this.isProviderUser || false;
        let res = await getServiceEngineerInit({ isProviderUser });
        if(res.success && res.code === 0) {
          res.result.buttonList.forEach(item => {
            this.btnsPermission[item.type] = item.visible;
          });// 按钮权限
          this.columns = res?.result?.allField?.filter(item => item.isHidden != 1)?.map(item => {
            item.show = true;
            item.tableName= 'engineer'
            return item;
          }) ?? [];
          if(this.haveUserNote){
            this.columns.unshift({
              displayName:this.$t('department.label.label6'),
              fieldName:'loginStatus',
              formType:'text',
              show:true,
            })
          }
          
          // 状态
          let fieldStatus = this.columns.filter(item => item.fieldName === 'status');
          if(fieldStatus && fieldStatus.length) {
            this.status = fieldStatus[0]?.setting?.dataSource || [];
          }
          this.columns.splice(3, 0, {fieldName:'qualificationNames', displayName:t('common.label.subCertifications'), formType:'text', isSystem:1, show:true, tableName:"engineer"})
          this.buildColumns();
        } else {
          this.$message.error(res.message || this.$t('serviceProvider.providerListInitError'));
        }
      } catch (e) {
        console.error(e);
      }
      return
    },

    // 处理表头数据
    buildColumns() {
      const localStorageData = this.getLocalStorageData();
      let columnStatus = localStorageData.columnStatus || [];

      const localColumns = columnStatus
          .map((i) => (typeof i == 'string' ? { field: i, show: true } : i))
          .reduce((acc, col, currentIndex) => {
            acc[col.field] = {
              field: col,
              index: currentIndex,
            }
            return acc
          }, {});

      let engineerFields = this.columns;
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        // 有本地缓存--列表排序
        engineerFields = this.buildSortFields(engineerFields, localColumns);
      }

      const columns =  engineerFields.map((col) => { // 选择列配置 是否勾选（显示）&宽度
        let show = col.show;
        let width = col.width;

        let localField = localColumns[col.fieldName]?.field || null;
        let fixLeft = localField?.fixLeft || null;

        if (null != localField) {
          if (localField.width) {
            width = typeof localField.width == 'number'
                ? `${localField.width}px`
                : localField.width;
          }
          show = localField.show !== false;
        }
        col.show = show;
        col.width = width;
        col.minWidth = col.width || 150;
        col.type = 'column';
        col['fixLeft'] = fixLeft && 'left'
        return col;
      }).filter(item => !['separator', 'attachment', 'info', 'autograph'].includes(item.formType))

      this.columns = []
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice())
      })
    },
    searchList() {
      this.page.pageNum = 1;
      this.search();
    },
    // 获取列表数据
    async search() {
      this.listLoading = true;
      try {
        const params = this.buildSearchParams();
        let res = await getEngineerPageList(params);
        if(res.success && res.code === 0) {
          let list = res?.result?.engineerList?.list;
          if (!list) this.page = new Page();
          this.page.merge(res.result.engineerList);
          this.dataList = list || [];
          this.matchSelected();
        }
      } catch (e) {
        console.error(e);
      } finally {
        this.listLoading = false;
      }
    },

    // 获取本地localstorage
    getLocalStorageData() {
      const dataStr = storageGet(ENGINEER_LIST_KEY, '{}');
      return JSON.parse(dataStr);
    },

    // 选择列排序
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = []

      originFields.forEach(originField => {
        let { fieldName } = originField
        let field = fieldsMap[fieldName]

        if (field) {
          let { index } = field
          fields[index] = originField
        } else {
          unsortedFields.push(originField)
        }
      })

      return fields.concat(unsortedFields)
    },

    // 构建搜索参数
    buildSearchParams() {
      let { pageNum, pageSize } = this.page;
      return {
        pageNum,
        pageSize,
        searchKey: this.deptKeyword,
        status: this.shareData?.status,
        tagId: this.shareData?.tagId,
        code: this.shareData?.code,
        name: this.shareData?.name,
        tenantProviderId: this.shareData?.tenantProviderId,
      }
    },

    // 保存数据到本地localstorage
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet(ENGINEER_LIST_KEY, JSON.stringify(data));
    },

    // 保存选择列配置
    saveColumnStatus(event) {
      let columns = event.data || []

      this.columns = []
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage()
      })
      this.$message.success(this.$t('common.base.saveSuccess'));
    },
    // 保存选择列配置到本地
    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.fieldName,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },

    handleSelection(selection){
      let tv = [];

      tv = this.multipleSelection.filter((ms) =>
          this.dataList.every((c) => c.loginUserId !== ms.loginUserId)
      );

      this.multipleSelection = _.uniqWith([...tv, ...selection], _.isEqual);
    },

    // 点击选择列
    handleSelectColumn() {
      this.$refs.advanced?.open(this.columns);
    },

    // 添加工程师（独立端）
    addEngineer() {
      let provide = {}
      if(this.shareData.tenantProviderId) {
        provide = {
          label: this.shareData.name,
          value: this.shareData.tenantProviderId,
        }
      }
     this.$refs.addUserRef?.openDialog(provide);
    },

    //设主派单员
    async setMainDispatcher() {
       this.$refs.mainDisRef?.openDialog(this.shareData?.tenantProviderId);
    },

    // 重置密码
    resetPassward(row) {
     this.$refs.resetPasRef?.openDialog(row.loginUserId);
    },

    // 启用停用工程师
    async stopEngineer(row) {
      try {
        let res = await openEngineer({ userId: row.loginUserId });
        this.$message({
          type: res.succ ? 'success' : 'error',
          message:  res.message,
          showClose: true,
          duration: 2000,
        });
        this.resetSearch();
      } catch (e) {
        console.error(e);
      }
    },

    // 注销工程师
    async logoutEngineer(row) {
      try {
        await this.$confirm( this.$t('serviceProvider.logoutEngineerAndResetDefaultStatus'), this.$t('serviceProvider.confirmLogoutEngineer'));
        let res = await unbindUser([row.loginUserId]);
        this.$message({
          type: res.success ? 'success' : 'error',
          message:  res.success ? this.$t('common.base.logoutSuccess') : res.message || this.$t('common.base.lououtFailed'),
          showClose: true,
          duration: 2000,
        });
        this.resetSearch(true);
      } catch (e) {
        console.error(e);
      }
    },

    // 删除账号
    async deleteEngineer(row) {
      try {
        await this.$confirm(this.$t('serviceProvider.confirmDeleteEngineer'), this.$t('serviceProvider.confirmDeleteEngineer'));
        let res = await deleteEngineer({ userId: row.loginUserId });
        this.$message({
          type: res.success ? 'success' : 'error',
          message: res.success ? this.$t('common.base.deleteSuccess') : res.message,
          showClose: true,
          duration: 2000,
        });
        this.resetSearch(true);
      } catch (e) {
        console.error(e);
      }
    },

    // 获取服务商状态
    getStatus(status) {
      return this.status.filter(item => item && item.value === status)[0]?.text || ''
    },

    // 地址
    getAddress(field) {
      if (!field) return ''
      return formatAddress(field)
    },

    // 授权工单类型&授权产品类型
    getAuthorize(authorizes) {
      if(Array.isArray(authorizes)) return authorizes.map(item => item && item.name).join('；')
    },

    // 授权区域
    getAreas(areas) {
      if(Array.isArray(areas)) return areas.map(item => item && item.all).join('、')
    },

    // 页码跳转
    handlePageJump(pageNum) {
      this.page.pageNum = pageNum;
      this.search();
    },

    // 页数修改
    handleSizeChange(pageSize) {
      this.saveDataToStorage(ENGINEER_PAGE_SIZE_KEY, pageSize);
      this.page.pageSize = pageSize;
      this.page.pageNum = 1;
      // 列表查询
      this.search();
    },

    gotoUrl(type, key = '', params = '') {
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum[type],
        key,
        params,
        fromId
      })
    },

    // 重置
    resetSearch(accountEnable = false) {
      this.page.pageNum = 1;
      // 列表查询
      this.search();
      accountEnable && this.$emit('refreshAccount')
    },

    // 表格高度计算
    knowTableContainerHeight() {
      // 表格默认最小 220
      let min = TABLE_HEIGHT_MIN;
      try {
        
        const windowClientHeight = window.innerHeight;
        
        const tableEl = this.$refs.tableRef?.$el;
        const tableElBounding = tableEl?.getBoundingClientRect();
        const top = tableElBounding?.top || 0;
        
        const footerEl = this.$refs.tableFooterContainer;
        const footerElClientHeight = footerEl?.clientHeight || 0;
        
        const appEl = document.querySelector('#app');
        const viewContainerEl = appEl.firstChild;
        const viewContainerElStyle = window.getComputedStyle(viewContainerEl);
        const viewContainerElPaddingBottom = viewContainerElStyle.getPropertyValue('padding-bottom');
        const viewContainerElPaddingBottomNum = parseInt(viewContainerElPaddingBottom, 10);
        
        min = windowClientHeight - top - footerElClientHeight - viewContainerElPaddingBottomNum;
        
        min = min > TABLE_HEIGHT_MIN ? min : TABLE_HEIGHT_MIN;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    debounceKnowTableContainerHeight: _.debounce(function() {
      this.knowTableContainerHeight();
    }, 500),
    // 清空选择框
    toggleClearSelection() {
      this.multipleSelection = [];
      this.$refs.tableRef.clearSelection();
    },

    // 把选中的匹配出来
    matchSelected() {
      if (this.multipleSelection.length) {
        this.$nextTick(() => {
          this.dataList.forEach(item => {
            if(this.multipleSelection.some(v=> item.loginUserId === v.loginUserId)){
              this.$refs.tableRef.toggleRowSelection(item, true);
            }
          });
        })
      }
    },

    //tab切换需求重置表格高度和刷新数据
    refreshEngineer() {
      this.search();
      this.$nextTick(() => {
        this.knowTableContainerHeight();
      })
    },

    // 跳转到人员地图
    gotoMap() {
      let engineerMap = {
        allProvider: true,
      }
      if(this.isEngineerList) {
        engineerMap.allProvider = false
        engineerMap.providerId = this.shareData?.tenantProviderId || ''
      }
      sessionStorage.setItem('engineer_condition', JSON.stringify(engineerMap))
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum.PageIntelligenceReport,
        params: 'menuName=PEREA&chartName=PERMAP',
        reload: true,
        fromId
      })
    }
  },
  watch: {
    shareData:{
      deep: true,
      handler(val) {
        if(val.hideTopTip) {
          this.knowTableContainerHeight();// 监听头部提示是否隐藏，隐藏的话调用
        }
        this.search();
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.engineer-list {
  height: 100%;
  overflow: visible;
  border-radius: 4px;
  padding: 0;
  .color-primary {
    color: $color-primary;
  }
  &-main {
    padding-right: 12px;
    background: white;
    padding-left: 12px;
    .main-btn {
      justify-content: end;
    }
    &-search {
      justify-content: space-between;
    }
    .search-input {
      width: 205px;
    }
    .engineer-info-name {
      display: flex;
      align-items: center;
    }
    .engineer-main-people {
      min-width: 64px;
      height: 22px;
      background: #FFFBE6;
      border-radius: 2px;
      border: 1px solid #FFE58F;
      font-size: 12px;
      font-weight: 400;
      color: #FAAD14;
      line-height: 22px;
      margin-left: 6px;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 0 6px;
    }
  }
  &-table {
    background-color: #fff;
    border-radius: 4px;
  }
  .c-primary {
    color: $color-primary;
  }
}
.engineer-over {
  // overflow: auto;
}
.just-end {
  justify-content: end;
}
.engineer-pad {
  padding-right: 12px;
}
</style>
<style lang="scss">
@import '@src/modules/dept/common.scss';
.more-tip {
  padding: 5px 0 !important;
}
.engineer-more {
  height: 30px;
  font-size: 14px;
  font-weight: 400;
  color: #000000;
  line-height: 22px;
  padding: 4px 12px;
  cursor: pointer;
  &:hover {
    background: rgba(0, 0, 0, 0.04);
    color: #000000;
  }
}
</style>